package com.dianpingmedia.wifitz.tcp.client;


import java.net.Socket;


public class TcpClient extends MyTcpBase {
    protected String m_strHost = "127.0.0.1";
    protected int m_iPort = 1200;


    public boolean connect() {
        return this.connect(this.m_strHost, this.m_iPort);
    }

    @SuppressWarnings("resource")
    public boolean connect(String strHost, int iPort) {
        try {
            Socket socket = new Socket(strHost, iPort);
            if (this.attachSocket(socket)) {
                this.m_strHost = strHost;
                this.m_iPort = iPort;
                return true;
            }
            socket = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void test() {
        for (int i = 0; i < 1000000; ++i) {
            //if( this.connect( "120.79.171.48", 1200 ) )
            if (this.connect("192.168.0.100", 1200)) {
                if (this.sendHandShake(100) == false) {
                    //return;
                }
            }

            try {
                Thread.sleep(1000 + (long) Math.random() * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.close();
        }

        int iRecvLength = this.read();
        if (iRecvLength <= 0) {
            return;
        }
        String strCmd = this.getRecvString();


        for (int i = 0; i < 10; ++i) {
            if (this.sendHandShake(i) == false) {
                return;
            }

            iRecvLength = this.read();
            if (iRecvLength <= 0) {
                return;
            }
            strCmd = this.getRecvString();

            if (this.sendHandShake(i) == false) {
                return;
            }
            //接收到命令
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean sendHandShake(int i) {
        String str = "I am Client！" + i + "Thread id =" + Thread.currentThread().getId();
        byte[] byData = str.getBytes();
        this.write(byData);
        return true;
    }
}
